from typing import Dict, Optional
from fastapi import FastAPI, Path, Query
import uvicorn
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None


# 除了路径参数 item_id 是必传的，查询参数 name 和请求体 item 都是可选非必传
@app.post('/items/{item_id}')
async def update_item(*, item_id: int = Path(default=..., description='item_id', gt=1, lt=20),
                      name: Optional[str] = Query(default=None, description="查询参数", min_length=0, max_length=20),
                      item: Optional[Item] = None):
    result = {"item_id": item_id}
    if name:
        result.update({"name": name})
    if item:
        result.update({"item": item})
    return result


# 多个 Request Body
# 自定义模型类 2
class User(BaseModel):
    username: str
    full_name: Optional[str] = None


@app.post("/items/{item_id}")
async def update_item(item_id: int,
                      item: Item,  # 指定第一个 Model 类型
                      user: User):  # 指定第二个 Model 类型
    results = {
        "item_id": item_id,
        "item": item,
        "user": user
    }
    return results


if __name__ == '__main__':
    uvicorn.run(app='main:app', host='127.0.0.1', port=8000, reload=True, debug=True)
